package com.sky.service.impl;



import com.google.common.collect.Lists;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {



    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //第一项   TurnoverReportVO----dateList
        List<LocalDate> dateList = new ArrayList<>();
        while(!begin.equals(end)){
            //获取日期的下一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        dateList.add(end.plusDays(1));
        String dateListString =StringUtils.join(dateList, ",");
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(dateListString);
        List<Double> turnoverList =  new ArrayList<>();
        //查询这个范围的数据
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //select sum(amount) from orders where orderTime between beginTime and endTime and status = 5
            //用map来封装参数
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumMap(map);
            turnover =  turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        String turnoverListString = StringUtils.join(turnoverList, ",");
        turnoverReportVO.setTurnoverList(turnoverListString);
        return turnoverReportVO;
    }

    // 用户统计
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //第一项   TurnoverReportVO----dateList
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            //获取日期的下一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dateListString =StringUtils.join(dateList, ",");
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            Integer totalUser = userMapper.sumMap(map);
            totalUser = totalUser == null? 0 :totalUser;
            totalUserList.add(totalUser);
            map.put("begin", beginTime);
            Integer newUser = userMapper.sumMap(map);
            newUser = newUser== null? 0 :newUser;
            newUserList.add(newUser);
        }
        String totalUserListString = StringUtils.join(totalUserList, ",");
        String newUserListString = StringUtils.join(newUserList, ",");

        //封装返回
        UserReportVO userReportVO =UserReportVO.builder()
                .dateList(dateListString)
                .totalUserList(totalUserListString)
                .newUserList(newUserListString)
                .build();

        return userReportVO;
    }

    //订单统计
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //第一项   TurnoverReportVO----dateList
        List<LocalDate> dateList = new ArrayList<>();
        while(!begin.equals(end)){
            //获取日期的下一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        dateList.add(end.plusDays(1));
        String dateListString =StringUtils.join(dateList, ",");
        //每日订单数和有效订单数
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //获取指定日期的订单数据
            Integer orderCount = sumOrdersMap(beginTime,endTime,null);
            orderCountList.add(orderCount);
            Integer validOrderCount = sumOrdersMap(beginTime,endTime,Orders.COMPLETED);
            validOrderCountList.add(validOrderCount);
        }

        String orderCountListString =StringUtils.join(orderCountList, ",");
        String validOrderCountListString = StringUtils.join(validOrderCountList, ",");
        //统计
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //计算
        Double orderCompletionRate=0.0;
        if(validOrderCount!=0){
            orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;
        }
        //构建封装并放回
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(dateListString)
                .orderCountList(orderCountListString)
                .validOrderCountList(validOrderCountListString)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }


    // 订单统计
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime =LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime =LocalDateTime.of(end, LocalTime.MAX);
        //在订单详情中查询  状态为完成的订单  多表查询  结合订单表
        List<GoodsSalesDTO> goodsSalesDTOs = orderMapper.getSalesTop10(beginTime, endTime);

        List<String> nameList=goodsSalesDTOs.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameListString = StringUtils.join(nameList, ",");
        List<Integer> numberList=goodsSalesDTOs.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberListString = StringUtils.join(numberList, ",");

        SalesTop10ReportVO salesTop10 = SalesTop10ReportVO.builder()
                .nameList(nameListString)
                .numberList(numberListString)
                .build();

        return salesTop10;
    }


    // 导出营业数据
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1.查询数据库,获取营业数据----最近30天的营业数据
        LocalDate begin = LocalDate.now().minusDays(30);
        // 结束日期
        LocalDate end = LocalDate.now().minusDays(1); // minusDays(1)表示减1天
        //处理
        BusinessDataVO businessDataVO = workSpaceService.
                getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),LocalDateTime.of(end, LocalTime.MAX));
        //2.通过poi 将数据写入到excel中
        InputStream in=
                this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //读出模板
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //填充数据
            //获取 sheet 页
            XSSFSheet sheet=excel.getSheet("Sheet1");
            //1.时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin+"至"+end);
            //获得第四行
            XSSFRow row = sheet.getRow(3);
            //2.营业额
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //3.订单完成率
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //4.新用户
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //下一行  获取第5行
            row = sheet.getRow(4);
            //5.有效订单
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //6.平均订单单价
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //从第8行开始，写入数据   for
            //从数据库 查询 明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO businessData = workSpaceService.
                        getBusinessData(LocalDateTime.of(date, LocalTime.MIN),LocalDateTime.of(date, LocalTime.MAX));
                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());//营业额
                row.getCell(3).setCellValue(businessData.getValidOrderCount());//有效订单
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());//订单完成率
                row.getCell(5).setCellValue(businessData.getUnitPrice());  //平均客单价
                row.getCell(6).setCellValue(businessData.getNewUsers());//新增用户
            }
            //3.通过输入流将Excel下载到浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //4.关闭流
            out.close();
            excel.close();
            log.info("导出Excel成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }




    //---------------------------------方法-------------------------------------------
    // 统计指定时间区间内的订单数据
    Integer sumOrdersMap(LocalDateTime beginTime, LocalDateTime endTime, Integer status){
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", status);
        Integer orderCount = orderMapper.sumOrdersMap(map);
        return orderCount == null ? 0 : orderCount;
    }





}
